//
//  YZWorkNoteListCell.m
//  VET
//
//  Created by 刘文靖 on 2018/7/10.
//  Copyright © 2018年 YZ. All rights reserved.
//

#import "YZWorkNoteListCell.h"
#import "YZWorkNoteLayout.h"
#import "YZWorkNoteModel.h"
#import "NSDate+YZDatePickView.h"
#import "YYControl.h"
#import "YZAutoItemModel.h"
#import "YZNoteAudioDisplayBtn.h"
@implementation YZWorkNoteTopToolView
- (instancetype)initWithFrame:(CGRect)frame {
    if (frame.size.width == 0 && frame.size.height == 0) {
        frame.size.width = kScreenWidth;
        frame.size.height = kWNCellTopTimeHeight;
    }
    self = [super initWithFrame:frame];
    self.exclusiveTouch = YES;
    
    _timetextLabel = [UILabel new];
    _timetextLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:16];
    _timetextLabel.textColor = kColorWithHex(0x9B9B9B);
    _timetextLabel.left = kWNCellPadding;
    _timetextLabel.size = CGSizeMake(128, 20);
    _timetextLabel.top = 18;
    [self addSubview:_timetextLabel];
    
    _manageButton = [[UIButton alloc] init];
    [_manageButton setTitle:@"处理" forState:UIControlStateNormal];
    _manageButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
    [_manageButton setTitleColor:kColorWithHex(0x32BE60) forState:UIControlStateNormal];
    _manageButton.size = CGSizeMake(28, 26);
    _manageButton.right = self.right - 18;
    _manageButton.centerY = _timetextLabel.centerY;
    [self addSubview:_manageButton];
    
    return self;
}
@end

@implementation YZWorkNoteBottomToolView
- (instancetype)initWithFrame:(CGRect)frame {
    if (frame.size.width == 0 && frame.size.height == 0) {
        frame.size.width = kScreenWidth;
        frame.size.height = kWNCellBottomToolHeight;
    }
    self = [super initWithFrame:frame];
    self.exclusiveTouch = YES;
    UILabel *classifyDescLabel = [UILabel new];
    classifyDescLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
    classifyDescLabel.textColor = kColorWithHex(0x9B9B9B);
    classifyDescLabel.text = @"分类: ";
    [self addSubview:classifyDescLabel];
    [classifyDescLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(kWNCellPadding);
        make.top.offset(18);
        make.height.mas_equalTo(12);
    }];
    
    _classifyLabel = [UILabel new];
    _classifyLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
    _classifyLabel.textColor = kColorWithHex(0x9B9B9B);
    _classifyLabel.text = @"未确定";
    [self addSubview:_classifyLabel];
    [_classifyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(classifyDescLabel.mas_right).offset(5);
        make.top.mas_equalTo(classifyDescLabel);
        make.height.mas_equalTo(12);
    }];
    
    UILabel *archiveDescLabel = [UILabel new];
    archiveDescLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
    archiveDescLabel.textColor = kColorWithHex(0x9B9B9B);
    archiveDescLabel.text = @"归属: ";
    [self addSubview:archiveDescLabel];
    [archiveDescLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.classifyLabel.mas_right).offset(30);
        make.top.mas_equalTo(classifyDescLabel);
        make.height.mas_equalTo(12);
    }];
    
    _archiveLabel = [UILabel new];
    _archiveLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
    _archiveLabel.textColor = kColorWithHex(0x9B9B9B);
    _archiveLabel.text = @"未确定";
    [self addSubview:_archiveLabel];
    [_archiveLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(archiveDescLabel.mas_right).offset(5);
        make.top.mas_equalTo(classifyDescLabel);
        make.height.mas_equalTo(12);
    }];
    
    return self;
}
@end

@implementation YZWorkNoteView
- (instancetype)initWithFrame:(CGRect)frame {
    if (frame.size.width == 0 && frame.size.height == 0) {
        frame.size.width = kScreenWidth;
        frame.size.height = 1;
    }
    self = [super initWithFrame:frame];
    self.backgroundColor = [UIColor clearColor];
    self.exclusiveTouch = YES;
    
    _contentView = [UIView new];
    _contentView.width = kScreenWidth;
    _contentView.height = 1;
    _contentView.backgroundColor = [UIColor whiteColor];
    [self addSubview:_contentView];
    /** 顶部 时间+处理按钮 */
    _topTool = [YZWorkNoteTopToolView new];
    [_contentView addSubview:_topTool];
    /** 文字内容 */
    _textLabel = [YYLabel new];
    _textLabel.left = kWNCellPadding;
    _textLabel.width = kWNCellContentWidth;
    _textLabel.textVerticalAlignment = YYTextVerticalAlignmentTop;
    _textLabel.displaysAsynchronously = YES;
    _textLabel.ignoreCommonProperties = YES;
    _textLabel.fadeOnAsynchronouslyDisplay = NO;
    _textLabel.fadeOnHighlight = NO;
    [_contentView addSubview:_textLabel];
    _showMoreButton = [[UIButton alloc] init];
    _showMoreButton.left = kWNCellPadding;
    _showMoreButton.width = kWNCellContentWidth;
    UILabel *showMoreLabel = [[UILabel alloc] init];
    showMoreLabel.text = @"查看全部";
    showMoreLabel.textColor = kColorWithHex(0x7a7a7a);
    showMoreLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
    showMoreLabel.size = CGSizeMake(56, 20);
    showMoreLabel.top = 31;
    showMoreLabel.centerX = kWNCellContentWidth * 0.5;
    
    UIImageView *arrowIV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"note_down_arrow"]];
    arrowIV.top = 33;
    arrowIV.left = CGRectGetMaxX(showMoreLabel.frame) + 4;
    
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame =CGRectMake(0, 0, kWNCellContentWidth, 64);
    gradientLayer.startPoint = CGPointMake(0.0f, 0.0f);
    gradientLayer.endPoint = CGPointMake(0.0f, 1.0f);
    gradientLayer.colors = @[(__bridge id)kColorWithHexAlpha(0xffffff, 0.09).CGColor,(__bridge id)kColorWithHexAlpha(0xffffff, 0.82).CGColor,(__bridge id)kColorWithHexAlpha(0xffffff, 1.0).CGColor];
    //gradientLayer.locations = @[@(0.2f),@(0.4f),@(0.6f),@(0.8f)];
    gradientLayer.type = kCAGradientLayerAxial;
    [_showMoreButton.layer addSublayer:gradientLayer];
    [_showMoreButton addSubview:showMoreLabel];
    [_showMoreButton addSubview:arrowIV];
    [_contentView addSubview:_showMoreButton];
    _showMoreButton.hidden = YES;
    /** 图片内容 */
    NSMutableArray *picViews = [NSMutableArray new];
    for (int i = 0; i < 9; i++) {
        YYControl *imageView = [YYControl new];
        imageView.size = CGSizeMake(100, 100);
        imageView.hidden = YES;
        imageView.clipsToBounds = YES;
        imageView.exclusiveTouch = YES;
        @weakify(self)
        imageView.touchBlock = ^(YYControl *view, YYGestureRecognizerState state, NSSet *touches, UIEvent *event) {
            @strongify(self)
            if (![self.cell.delegate respondsToSelector:@selector(cell:didClickImageAtIndex:)]) return;
            if (state == YYGestureRecognizerStateEnded) {
                UITouch *touch = touches.anyObject;
                CGPoint p = [touch locationInView:view];
                if (CGRectContainsPoint(view.bounds, p)) {
                     [self.cell.delegate cell:self.cell didClickImageAtIndex:i];
                }
            }
        };
        [picViews addObject:imageView];
        [_contentView addSubview:imageView];
    }
    _picViews = picViews;
    
    _audioDisplayBtn = [[YZNoteAudioDisplayBtn alloc] initWithDisplayType:YZNoteAudioDisplayNoteList audioUrl:nil];
    _audioDisplayBtn.left = kWNCellPadding;
    _audioDisplayBtn.width = kWNCellContentWidth;
    [_contentView addSubview:_audioDisplayBtn];
    /** 底部 分类+归档 */
    _bottomTool = [YZWorkNoteBottomToolView new];
    [_contentView addSubview:_bottomTool];
    
    return self;
}

- (void)setLayout:(YZWorkNoteLayout *)layout{
    _layout = layout;
    self.height = layout.height;
    _contentView.top = layout.marginTop;
    _contentView.height = layout.height - layout.marginTop - layout.marginBottom;
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:(layout.note.createTime)] ;
    _topTool.timetextLabel.text = [NSDate yz_getDateString:date format:@"MM月dd日HH:mm"];
    _bottomTool.classifyLabel.text = layout.note.noteType.itemValue?:@"未确定";
    _bottomTool.archiveLabel.text = layout.note.isArchived?@"已归档":@"未归档";
    CGFloat top = 0;
    _topTool.top = top;
    top += kWNCellTopTimeHeight;
    
    _textLabel.top = top;
    _textLabel.height = layout.textHeight;
    _textLabel.textLayout = layout.textLayout;
    top += layout.textHeight;
    if (layout.shouldShowMoreButton) {
        _showMoreButton.hidden = NO;
        _showMoreButton.top = top - 24;
        _showMoreButton.height = 64;
    }else{
       _showMoreButton.hidden = YES;
    }
    if (layout.picHeight > 0) {
        top += layout.textHeight?kWNCellPaddingPic:0;
        if (layout.note.attachType == YZWorkNoteAttachTypeAudio) {
            _audioDisplayBtn.height = layout.picHeight;
            _audioDisplayBtn.top = top;
            _audioDisplayBtn.audioUrl = _layout.note.attachmentList.firstObject.attachmentUrl;
            _audioDisplayBtn.totalTimeInterval = layout.note.attachmentList.firstObject.mediaTime;
            _audioDisplayBtn.hidden = NO;
            [self _hideImageViews];
        }else{
            _audioDisplayBtn.hidden = YES;
            [self _setImageViewWithTop:top];
        }
    }else{
        _audioDisplayBtn.hidden = YES;
        [self _hideImageViews];
    }
    _bottomTool.bottom = _contentView.height;
}

- (void)_hideImageViews {
    for (UIView *imageView in _picViews) {
        imageView.hidden = YES;
    }
}

- (void)_setImageViewWithTop:(CGFloat)imageTop{
    CGSize picSize =  _layout.picSize;
    NSArray *pics =  _layout.note.attachmentList;
    int picsCount = (int)pics.count;
    for (int i = 0; i < 9; i++) {
        UIView *imageView = _picViews[i];
        if (i >= picsCount) {
            [imageView.layer cancelCurrentImageRequest];
            imageView.hidden = YES;
        } else {
            CGPoint origin = {0};
            switch (picsCount) {
                case 1: {
                    origin.x = kWNCellPadding;
                    origin.y = imageTop;
                } break;
                case 4: {
                    origin.x = kWNCellPadding + (i % 2) * (picSize.width + kWNCellPaddingPic);
                    origin.y = imageTop + (int)(i / 2) * (picSize.height + kWNCellPaddingPic);
                } break;
                default: {
                    origin.x = kWNCellPadding + (i % 3) * (picSize.width + kWNCellPaddingPic);
                    origin.y = imageTop + (int)(i / 3) * (picSize.height + kWNCellPaddingPic);
                } break;
            }
            imageView.frame = (CGRect){.origin = origin, .size = picSize};
            imageView.hidden = NO;
            [imageView.layer removeAnimationForKey:@"contents"];
            YZAttachmentModel *attachment = pics[i];
            if ([attachment.mediaType isEqualToString:@"video/mp4"]) {
                if (!self.videoTipView) {
                    self.videoTipView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ico_quanzi_video_play"]];
                    [imageView addSubview:self.videoTipView];
                    [self.videoTipView mas_makeConstraints:^(MASConstraintMaker *make) {
                        make.center.offset(0);
                    }];
                }else{
                    self.videoTipView.hidden = NO;
                }
            }else{
                self.videoTipView.hidden = YES;
            }
            @weakify(imageView);
            [imageView.layer setImageWithURL:attachment.url
                                 placeholder:nil
                                     options:YYWebImageOptionAvoidSetImage
                                  completion:^(UIImage *image, NSURL *url, YYWebImageFromType from, YYWebImageStage stage, NSError *error) {
                                      @strongify(imageView);
                                      if (!imageView) return;
                                      if (image && stage == YYWebImageStageFinished) {
                                          int width = image.size.width;
                                          int height = image.size.height;
                                          CGFloat scale = (height / width) / (imageView.height / imageView.width);
                                          if (scale < 0.99 || isnan(scale)) { // 宽图把左右两边裁掉
                                              imageView.contentMode = UIViewContentModeScaleAspectFill;
                                              imageView.layer.contentsRect = CGRectMake(0, 0, 1, 1);
                                          } else { // 高图只保留顶部
                                              imageView.contentMode = UIViewContentModeScaleToFill;
                                              imageView.layer.contentsRect = CGRectMake(0, 0, 1, (float)width / height);
                                          }
                                          ((YYControl *)imageView).image = image;
                                          if (from != YYWebImageFromMemoryCacheFast) {
                                              CATransition *transition = [CATransition animation];
                                              transition.duration = 0.15;
                                              transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
                                              transition.type = kCATransitionFade;
                                              [imageView.layer addAnimation:transition forKey:@"contents"];
                                          }
                                      }
                                  }];
        }
    }
}
@end

@implementation YZWorkNoteListCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    _noteView = [YZWorkNoteView new];
    _noteView.cell = self;
    self.contentView.backgroundColor = kColorWithHex(0xF6F7F8);
    [self.contentView addSubview:_noteView];
    @weakify(self)
    [_noteView.topTool.manageButton addBlockForControlEvents:UIControlEventTouchUpInside block:^(id sender) {
        @strongify(self)
        if (self.delegate && [self.delegate respondsToSelector:@selector(cellDidClickManage:)]) {
            [self.delegate cellDidClickManage:self];
        }
    }];
    [_noteView.showMoreButton addBlockForControlEvents:UIControlEventTouchUpInside block:^(id sender) {
        @strongify(self)
        if (self.delegate && [self.delegate respondsToSelector:@selector(cellDidClickMoreButton:)]) {
            [self.delegate cellDidClickMoreButton:self];
        }
    }];
    return self;
}


- (void)setLayout:(YZWorkNoteLayout *)layout {
    self.height = layout.height;
    self.contentView.height = layout.height;
    _noteView.layout = layout;
}

@end
